/**
 * 鸡兔同笼：自动检查并尝试修复答案
 */

const fs = require('fs');
const path = require('path');

const ROOT = path.join(__dirname, '..', '..');
const FILE = path.join(ROOT, 'questions', 'primary-school', '鸡兔同笼.ts');

function read(file) { return fs.readFileSync(file, 'utf-8'); }
function write(file, content) { fs.writeFileSync(file, content, 'utf-8'); }

function extract(ts) {
  const m = ts.match(/export\s+const\s+([A-Za-z0-9_\u4e00-\u9fa5]+)\s*=\s*(\[[\s\S]*?\]);/m);
  if (!m) throw new Error('无法解析导出的数组');
  return { name: m[1], array: m[2] };
}

function parseArray(lit) { try { return eval(`(${lit})`); } catch { return null; } }
function s(str){ return JSON.stringify(String(str)).slice(1,-1); }

function solveHeadsFeet(stem){ const m = stem.match(/共有头(\d+)个.*?脚(\d+)只/); if(!m) return null; const H=+m[1],F=+m[2]; const c=(4*H-F)/2,r=H-c; if(!Number.isInteger(c)||!Number.isInteger(r)||c<0||r<0) return {ok:false}; return {ok:true,c,r,H,F}; }
function solveDiffWithHeads(stem){ const m=stem.match(/共有头(\d+)个.*?(鸡|兔)比(兔|鸡)多(\d+)只/); if(!m) return null; const H=+m[1], a=m[2], b=m[3], d=+m[4]; if(a==='鸡'&&b==='兔'){ const r=(H-d)/2,c=r+d; if(Number.isInteger(c)&&Number.isInteger(r)&&c>=0&&r>=0) return {ok:true,c,r,H}; } if(a==='兔'&&b==='鸡'){ const c=(H-d)/2,r=c+d; if(Number.isInteger(c)&&Number.isInteger(r)&&c>=0&&r>=0) return {ok:true,c,r,H}; } return {ok:false}; }
function solveFeetDiffWithHeads(stem){ const m=stem.match(/共有头(\d+)个.*?(兔的脚数比鸡的脚数多|鸡脚数比兔脚数少)(\d+)只/); if(!m) return null; const H=+m[1], diff=+m[3]; if(diff%2) return {ok:false}; const t=diff/2; const r=(H+t)/3,c=H-r; if(Number.isInteger(c)&&Number.isInteger(r)&&c>=0&&r>=0) return {ok:true,c,r,H}; return {ok:false}; }
function calc(stem){ return solveHeadsFeet(stem)||solveDiffWithHeads(stem)||solveFeetDiffWithHeads(stem); }

function rebuild(name, arr){
  const objs = arr.map(q=>`  { stem: "${s(q.stem)}", difficulty: ${q.difficulty}, answer: [${Array.isArray(q.answer)?q.answer.map(v=>typeof v==='number'?v:`"${s(v)}"`).join(', '):q.answer}], ${q.hint1?`hint1: "${s(q.hint1)}", `:''}${q.hint2?`hint2: "${s(q.hint2)}", `:''}solution: "${s(q.solution)}" }`).join(',\n');
  return `// 鸡兔同笼问题 - 自动修复版\nexport const ${name} = [\n${objs}\n];\n\nexport default ${name};\n`;
}

function main(){
  const ts = read(FILE);
  const {name, array} = extract(ts);
  const data = parseArray(array);
  if(!Array.isArray(data)) throw new Error('数组解析失败');
  let changed=0; const issues=[];
  const fixed = data.map((q,i)=>{
    const r = calc(q.stem||'');
    if(!r||r.ok===false){ return q; }
    const expected=[r.c,r.r];
    const ans = Array.isArray(q.answer)?q.answer:[q.answer];
    if(ans.length>=2 && ans[0]===expected[0] && ans[1]===expected[1]) return q;
    changed++; const nq={...q};
    nq.answer=expected;
    nq.solution=`【自动校正】设鸡${expected[0]}只，兔${expected[1]}只。验证：头数=${expected[0]}+${expected[1]}=${r.H??'?'}；脚数=${expected[0]}×2+${expected[1]}×4=${expected[0]*2+expected[1]*4}`;
    issues.push({index:i+1, from:ans, to:expected, stem:q.stem});
    return nq;
  });
  if(changed>0){ write(FILE, rebuild(name, fixed)); }
  const out=path.join(ROOT,'math-academy','docs'); if(!fs.existsSync(out)) fs.mkdirSync(out,{recursive:true});
  fs.writeFileSync(path.join(out,'auto-fix-chicken-rabbit.json'), JSON.stringify({file:FILE, changed, total:data.length, issues},null,2));
  console.log(`完成：共${data.length}题，修复${changed}题。`);
}

main();

